package com.leoman.common.filter;

import com.leoman.common.core.ErrorType;
import com.leoman.common.logger.Logger;
import com.leoman.entity.Constant;
import com.leoman.exception.UserNotFindException;
import com.leoman.exception.UserStatusErrorException;
import com.leoman.userapi.service.UserInfoService;
import com.leoman.utils.BeanUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.Result;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by wangbin on 2015/8/10.
 */
public class UserStatusFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        url = url.substring(contextPath.length());
        Logger.info(contextPath + ", " + url);

        String userIdStr = httpRequest.getParameter("userId");
        if (StringUtils.isEmpty(userIdStr)) {
            chain.doFilter(request, response);
            return;
        }

        Long userId = Long.parseLong(userIdStr);

        UserInfoService userInfoService = (UserInfoService) BeanUtils.getBean("userInfoServiceImpl");
        Object object = null;
        try {
            userInfoService.getUserInfo(userId);
            chain.doFilter(request, response);
        } catch (UserNotFindException e) {
            object = Result.failureApi(ErrorType.ERROR_CODE_0003);
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.obj2ApiJson(object)); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        } catch (UserStatusErrorException e1) {
            object = Result.failureApi(ErrorType.ERROR_CODE_00036);
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.obj2ApiJson(object)); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        }
    }

    @Override
    public void destroy() {

    }
}